/*
 * Copyright 2008 the Breachwalls OSS project and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package com.breachwalls.quasar.datatype.generic;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import com.breachwalls.quasar.datatype.Datatype;

/**
 * 汎用列挙型データタイプ.
 * @author todoken
 * @version $Revision: 48 $
 */
public class GenericEnumeration extends GenericDatatype {

    /**
     * シリアルバージョンID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * 列挙型を解決するSTATICメソッドの名称.
     */
    private static final String RESOLVED_METHOD_NAME = "valueOf";

    /**
     * 列挙型のキー.
     */
    private String key;

    /**
     * コンストラクタ.
     * @param key 列挙型が保持する値
     */
    public GenericEnumeration(final String key) {
        this.key = key;
    }

    public static <E extends GenericEnumeration> Map<String, E> toMap(E... elements) {
        Map<String, E> map = new HashMap<String, E>();
        for (E element : elements) {
            String key = element.getKey();
            map.put(key, element);
        }
        return map;
    }

    @SuppressWarnings("unchecked")
    public static <E extends GenericEnumeration> E valueOf(final Class<?> clazz, final String key) {
        final Method[] candicates = clazz.getMethods();
        Method matchMethod = null;
        for (Method candicate : candicates) {
            int size = candicate.getParameterTypes().length;
            if (candicate.getName().equals(RESOLVED_METHOD_NAME) && size == 1) {
                matchMethod = candicate;
                break;
            }
        }
        if (matchMethod == null || !Modifier.isStatic(matchMethod.getModifiers())) {
            throw new UnsupportedOperationException("[" + clazz
                    + "] must be have 'static valueOf(String key)' method.");
        }
        Object result = null;
        try {
            result = matchMethod.invoke(null, key);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        } catch (InvocationTargetException e) {
            throw new IllegalArgumentException(e);
        }
        return (E) result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isNull() {
        return key == null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int length() {
        if (key == null) {
            return 0;
        }
        return key.length();
    }

    /**
     * 列挙型が保持しているキーを取得する.
     * @return 列挙型が保持しているキー
     */
    protected final String getKey() {
        return key;
    }

    /**
     * 列挙型の値を取得する.
     * @return 列挙型の値
     */
    public final String value() {
        return getKey();
    }

    /**
     * 列挙型の名称を取得する.
     * @return 列挙型の名称
     */
    public String name() {
        return getKey();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int compareTo(final Datatype datatype) {
        if (datatype != null && datatype instanceof GenericEnumeration) {
            GenericEnumeration target = (GenericEnumeration) datatype;
            if (target.getKey() != null) {
                return target.getKey().compareTo(getKey());
            }
        }
        return super.compareTo(datatype);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return key;
    }

}
